package anet

import (
	"gitee.com/AlexWoo/arpc"
)

var (
	cPool = arpc.NewPool(func() any { return &connection{} })
)

func getConnection(conn Conn) *connection {
	c := cPool.Get().(*connection)

	c.conn = conn
	if c.sess == nil {
		c.sess = map[string]*session{}
	} else {
		clear(c.sess)
	}

	return c
}

func putConnection(c *connection) {
	cPool.Put(c)
}

type connection struct {
	conn Conn
	sess map[string]*session
}

func (c *connection) bindSession(s *session) {
	c.sess[s.name] = s
}

func (c *connection) unbindSession(s *session) {
	delete(c.sess, s.name)

	if len(c.sess) == 0 {
		c.conn.Close()
		putConnection(c)
	}
}
